﻿using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace Change.uc
{
    public partial class ucItems : UserControl
    {
        SQLiteConnection conn;
        //定义委托
        delegate void inittvItemsDelegate();
        delegate void AsynUpdateUI1(string step);   //更新UI1
        delegate void AsynUpdateUI2(TreeNode root);//更新UI2

        public delegate void UpdateUI(string step);//声明一个更新主线程的委托
        public UpdateUI UpdateUIDelegate;

        public delegate void AccomplishTask(TreeNode root);//声明一个在完成任务时通知主线程的委托
        public AccomplishTask TaskCallBack;

        string yearID;

        public ucItems()
        {
            InitializeComponent();
            twItems.Nodes.Add("正在连接数据库");
            yearID = getYearID();

            UpdateUIDelegate += UpdataUIStatus;//绑定更新任务状态的委托
            TaskCallBack += Accomplish;//绑定完成任务要调用的委托
            //启动线程
            Thread thread = new Thread(intitvItems);
            thread.IsBackground = true;
            thread.Start();
            //intitvItems();
        }
        //更新UI
        private void UpdataUIStatus(string step)
        {
            if (InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI1(delegate (string s)
                {
                    //this.pgbWrite.Value += s;
                    //this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
                    twItems.Nodes.Add(s);
                }), step);
            }
        }

        //完成任务时需要调用
        private void Accomplish(TreeNode root)
        {
            if (InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI2(delegate (TreeNode rt)
                {
                    //this.pgbWrite.Value += s;
                    //this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
                    twItems.Nodes.Clear();
                    twItems.Nodes.Add(rt);
                }), root);
            }
        }

        private void intitvItems()
        {
            TreeNode root = new TreeNode();


            root.Tag = 0;
            root.Text = "物品数据库-" + yearID;
            root.Expand();
            //   twItems.Nodes.Add(root);
            try
            {
                //连接网络数据库
                conn = new SQLiteConnection("Data Source=db/eve.db;Version=3;");
                conn.Open();

                UpdateUIDelegate("数据库已连接，正在加载数据...");
            }
            catch (Exception ex)
            {
                throw ex;
            }


            setTreeView(root, 0);
            UpdateUIDelegate("市场组数据加载完毕，正在加载物品数据");
            setTreeViewLeaf(root);
            UpdateUIDelegate("物品组数据加载完毕.");
            TaskCallBack(root);

        }

        private void setTreeViewLeaf(TreeNode tr1)
        {

            foreach (TreeNode node in tr1.Nodes)
            {
                //查找树的叶子节点
                if (node.Nodes.Count == 0)
                {
                    addNodeLeaf(node);

                }
                else
                {
                    findTreeViewLeaf(node);
                }
                UpdateUIDelegate("加载物品组" + node.Text);
            }

        }

        private void setTreeView(TreeNode tr1, int parentId)
        {
            string sql;
            if (parentId == 0)
                sql = "select marketGroupID,marketGroupName_zh,parentGroupID from invmarketgroups where parentGroupID is null";
            else
                sql = "select marketGroupID,marketGroupName_zh,parentGroupID from invmarketgroups where parentGroupID=" + parentId;
            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);

            DataTable dt = new DataTable();
            reader.Fill(dt);

            if (dt.Rows.Count > 0)
            {

                int pId = -1;
                foreach (DataRow row in dt.Rows)
                {
                    TreeNode node = new TreeNode();
                    node.Text = row[1].ToString();
                    node.Tag = Convert.ToInt32(row[0]);
                    if (row[2] is System.DBNull)
                        pId = 0;
                    else
                        pId = Convert.ToInt32(row[2]);
                    if (pId == 0)
                    {
                        //添加根节点
                        tr1.Nodes.Add(node);
                    }
                    else
                    {
                        //添加根节点之外的其他节点
                        RefreshChildNode(tr1, node, pId);
                    }
                    //查找以node为父节点的子节点
                    setTreeView(tr1, Convert.ToInt32(node.Tag));

                }
            }
        }

        private string getYearID()
        {
            FileStream fs = new FileStream("db/eve.cfg", FileMode.Open, FileAccess.Read);

            StreamReader sr = new StreamReader(fs);

            string yearid = sr.ReadToEnd();

            return yearid;
            throw new NotImplementedException();
        }
        /// <summary>
        /// 第二层遍历，加速函数
        /// </summary>
        /// <param name="tr1"></param>
        private void findTreeViewLeaf(TreeNode tr1)
        {
            foreach (TreeNode node in tr1.Nodes)
            {
                //查找树的叶子节点
                if (node.Nodes.Count == 0)
                {
                    addNodeLeaf(node);

                }
                else
                {
                    flashTreeViewLeaf(node);
                }

            }
        }
        /// <summary>
        /// 第三层遍历，加速函数
        /// </summary>
        /// <param name="node"></param>
        private void flashTreeViewLeaf(TreeNode tr1)
        {
            foreach (TreeNode node in tr1.Nodes)
            {
                //查找树的叶子节点
                if (node.Nodes.Count == 0)
                {
                    addNodeLeaf(node);

                }
                else
                {
                    flashTreeViewLeaf(node);
                }

            }
        }


        /// <summary>
        /// 添加叶子节点
        /// </summary>
        /// <param name="node"></param>
        private void addNodeLeaf(TreeNode node)
        {
            int pid = Convert.ToInt32(node.Tag);

            string sql = "select typeID,typeName_zh from invtypes where marketGroupID=" + pid;

            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);

            DataTable dtLeaf = new DataTable();

            reader.Fill(dtLeaf);
            if (dtLeaf.Rows.Count > 0)
            {
                foreach (DataRow dr in dtLeaf.Rows)
                {
                    TreeNode nodeleaf = new TreeNode();
                    nodeleaf.Text = dr[1].ToString();
                    nodeleaf.Tag = Convert.ToInt32(dr[0]);

                    node.Nodes.Add(nodeleaf);
                }
            }
        }
        //处理根节点的子节点的子节点
        private void FindChildNode(TreeNode tNode, TreeNode treeNode, int parentId)
        {
            foreach (TreeNode node in tNode.Nodes)
            {
                if (Convert.ToInt32(node.Tag) == parentId)
                {
                    node.Nodes.Add(treeNode);
                    return;
                }
                else if (node.Nodes.Count > 0)
                {
                    FindChildNode(node, treeNode, parentId);
                }

            }

        }

        //处理根节点的子节点
        private void RefreshChildNode(TreeNode tr1, TreeNode treeNode, int parentId)
        {
            foreach (TreeNode node in tr1.Nodes)
            {
                if (Convert.ToInt32(node.Tag) == parentId)
                {
                    node.Nodes.Add(treeNode);
                    return;
                }
                else if (node.Nodes.Count > 0)
                {
                    FindChildNode(node, treeNode, parentId);
                }
            }
        }

        private void twItems_NodeMouseDoubleClick_1(object sender, TreeNodeMouseClickEventArgs e)
        {
            int typeID = Convert.ToInt32(e.Node.Tag);
            if (e.Node.Nodes.Count > 0)
                return;
            

            string sql = "select typeDescription_zh from invtypes where typeID=" + typeID;

            SQLiteDataAdapter reader = new SQLiteDataAdapter(sql, conn);

            DataTable dt = new DataTable();
            reader.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                webInstroduce.DocumentText = dt.Rows[0][0].ToString();


            }
            else
                webInstroduce.DocumentText = "未找到物品信息";

            sql = "select traitText_zh from invtraits where typeID=" + typeID;

            reader = new SQLiteDataAdapter(sql, conn);

            dt = new DataTable();
            reader.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                 webAttr.DocumentText = dt.Rows[0][0].ToString();
            }
            else
                webAttr.DocumentText = "未找到物品属性";
        }
    }
}
